package at.studentinformation;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBManager extends SQLiteOpenHelper{
 
    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/at.studentinformation/databases/";
 
    private static String DB_NAME = "StudentSqlite";
 
    private SQLiteDatabase myDataBase; 
 
    private final Context myContext;
 
    public DBManager(Context context) {
 
    	super(context, DB_NAME, null, 1);
        this.myContext = context;
        
   }	
 
    //Creates a empty database on the system and rewrites it with your own database.
    public void createDataBase(){
 
    	boolean dbExist = checkDataBase();
 
    	if(dbExist){
    		//do nothing - database already exist
    	}
    	else
    	{
    		//By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
    		try
    		{
    			this.getReadableDatabase();
    		}
    		catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}
 
        	try 
        	{
    			copyDataBase();
    		}
        	catch (Exception e) 
        	{
        		throw new Error("Error copying database");
        	}
    	}
 
    }
 
    private boolean checkDataBase(){
 
    	SQLiteDatabase checkDB = null;
 
    	try{
    		String myPath = DB_PATH + DB_NAME;
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    	}catch(SQLiteException e){
    	}
 
    	if(checkDB != null){
    		checkDB.close();
    	}
 
    	return checkDB != null ? true : false;
    }
 
    //Copy your db into system
    private void copyDataBase(){
    	try
    	{
	    	//Open your local db as the input stream
	    	InputStream myInput = myContext.getAssets().open(DB_NAME);
	 
	    	// Path to the just created empty db
	    	String outFileName = DB_PATH + DB_NAME;
	 
	    	//Open the empty db as the output stream
	    	OutputStream myOutput = new FileOutputStream(outFileName);
	 
	    	//transfer bytes from the inputfile to the outputfile
	    	byte[] buffer = new byte[1024];
	    	int length;
	    	while ((length = myInput.read(buffer))>0){
	    		myOutput.write(buffer, 0, length);
	    	}
	 
	    	//Close the streams
	    	myOutput.flush();
	    	myOutput.close();
	    	myInput.close();
	    }
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
    }
 
    public void openDataBase() throws SQLException{
    	try
    	{
	    	//Open the database
	        String myPath = DB_PATH + DB_NAME;
	    	myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    }
 
    @Override
	public synchronized void close() {
    	    if(myDataBase != null)
    		    myDataBase.close();
    	    super.close();
	}
 
	@Override
	public void onCreate(SQLiteDatabase db) {
 
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
	}
 
	public void Subject_Insert(Subject subject)
	{
		try
		{				
			ContentValues value = new ContentValues();
			value.put("SubjectId", subject.SubjectId);
			value.put("SubjectName", subject.SubjectName);
			value.put("SubjectViName", subject.SubjectViName);
			value.put("Credit", subject.Credit);
			myDataBase.insert("tdmh", null, value);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public void Point_Insert(Point point)
	{
		try
		{				
			ContentValues value = new ContentValues();
			value.put("SubjectId", point.SubjectId);
			value.put("StudentId", point.StudentId);
			value.put("SemesterId", point.SemesterId);
			value.put("PointNumber", point.PointNumber);
			myDataBase.insert("diem", null, value);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public void Schedule_Insert(Schedule schedule)
	{
		try
		{				
			ContentValues value = new ContentValues();
			value.put("SubjectId", schedule.SubjectId);
			value.put("StudentId", schedule.StudentId);
			value.put("SemesterId", schedule.SemesterId);
			value.put("Day", schedule.Day);
			value.put("Starthour", schedule.Starthour);
			value.put("Hour", schedule.Hour);
			value.put("Room", schedule.Room);
			value.put("Popular", schedule.Popular);
			value.put("Date", schedule.Date);
			value.put("Week", schedule.Week);
			myDataBase.insert("tkb_sv", null, value);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public void News_Insert(News news)
	{
		try
		{				
			ContentValues value = new ContentValues();
			value.put("Id", news.Id);
			value.put("Title", news.Title);
			value.put("Content", news.Content);
			value.put("Hot", news.Hot);
			value.put("CategoryId", news.CategoryId);
			value.put("Date", news.Date.toString());
			value.put("IsRead", news.IsRead);
			myDataBase.insert("noi_bo_news", null, value);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
		
	public void SubjectList_Insert(ArrayList<Subject> input)
	{
		try
		{				
			for(Subject temp : input) {
				Subject_Insert(temp);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public void PointList_Insert(ArrayList<Point> input)
	{
		try
		{				
			for(Point temp : input) {
				Point_Insert(temp);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public void ScheduleList_Insert(ArrayList<Schedule> input)
	{
		try
		{				
			for(Schedule temp : input) {
				Schedule_Insert(temp);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public void NewsList_Insert(ArrayList<News> input)
	{
		try
		{				
			for(News temp : input) {
				News_Insert(temp);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
		
	public ArrayList<String> GetSemesterIdByStudentId()
	{
		ArrayList<String> result = new ArrayList<String>();
		try
		{		
			Cursor c = myDataBase.rawQuery("Select SemesterId from diem where masv=" + Common.userName , null);
			while(c.moveToNext())
			{
				result.add(c.getString(0));
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return result;
	}
	
	public String GetListSubjectId_From_CurrentPointListByStudentId()
	{
		String result = "";
		try
		{
			Cursor c = myDataBase.rawQuery("select SubjectId from diem where StudentId=" + Common.userName, null);
			while(c.moveToNext())
			{
				result+= c.getString(0) + ",";
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		if(result!="")
			result=result.substring(0, result.length()-1);
		return result;
	}
}